﻿import mx.utils.Delegate;
import cn.eminia.A2.preLoader.LoadAsBitmap;
import flash.display.BitmapData;

/**
 * ...
 * @author wangjun
 */

class cn.eminia.A2.preLoader.ImgLoader {
	var arr:Array;
	var max:Object;
	var cmax:Object;
	var ccur:Object;
	var baseLoader:LoadAsBitmap; 
	//
	var count:Number; 
	var vars:Object;
	var scope; 
	var bmArr;
	function ImgLoader(scope:MovieClip, vars:Object) {
		cmax={}
		this.scope = scope;
		arr = []; 
		count = 0;
		this.vars = vars;  
		bmArr={}
	}
	function add(url:String) {
		if (!url || !(String(url))) {
			throw new Error("!!![ImgLoader] url 空");
		}
		arr.push(url);
		cmax[url]=0;
	}
	function doMax(nn){
		max+=nn ;
	}
	function doCount(id,ttl){
		var mm=0;
		for(var i=0;i<arr.length;i++){
			if(id==arr[i]){
				ccur[id]=ttl
			}
			mm+=ccur[arr[i]]
		}
		return mm
	}
	function start() {
		max=0;
		ccur=[];
		for(var i=0;i<arr.length;i++){
			ccur[arr[i]]=0;
		}  
		doMax['count']=0;
		for (var i = 0; i<arr.length; i++) {
			baseLoader = new  LoadAsBitmap(this, {stt:function (evt) { 
				Delegate.create(this.scope,  this.vars.stt1)({id:evt.id}) 
			}, pro:function (evt) {
				Delegate.create(this.scope,  this.vars.pro1)({id:evt.id,cur:evt.cur,max:evt.max})
				if(doMax['count'] == arr.length){  
					var ld=( doCount(evt.url,evt.cur) ); 					
					Delegate.create(this.scope, this.vars.pro)({per:Math.round(ld/max*100), cur:ld, max:max }); 
					return;
				} 
				if(!cmax[evt.url]){
					cmax[evt.url]=1
					doMax['count']++;
					doMax(evt.max) 
				} 
			}, ok: function (evt) {
				bmArr[evt.url] = evt.bm; 
				Delegate.create(this.scope, this.vars.ok1)({bm:evt.bm,url:evt.url,id:evt.id}); 
				count++; 
				if (count == arr.length) Delegate.create(this.scope, this.vars.ok)(); 
			} });
			baseLoader.load(arr[i],i);
		}
	}
	public function apply(bm:BitmapData,ctt:MovieClip):Boolean {
	//	trace('ImgLoader::apply() bm = ' +bm  )
		if(bm.constructor!=BitmapData) return false;
		 ctt.attachBitmap( bm, 0);
		 return true;
	}
	static public function applyBm(bm:BitmapData,ctt:MovieClip):Boolean {
	//	trace('ImgLoader::apply() bm = ' +bm  )
		if(bm.constructor!=BitmapData) return false;
		 ctt.attachBitmap( bm, 0);
		 return true;
	}
	function get(id):flash.display.BitmapData{
		trace(bmArr[id])
		return bmArr[id]
	}
	function dispose() {
		arr = [];
		max=[]
	}
}
